<template>
  <div class="project-list">
    <div class="page-header">
      <div class="header-left">
        <h1>项目管理</h1>
        <p>管理和查看所有项目</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="createProject">
          <el-icon><Plus /></el-icon>
          创建项目
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-input
          v-model="searchQuery"
          placeholder="搜索项目名称或描述"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="filter-right">
        <el-select
          v-model="statusFilter"
          placeholder="项目状态"
          style="width: 120px"
          clearable
          @change="handleFilter"
        >
          <el-option label="进行中" value="进行中" />
          <el-option label="已完成" value="已完成" />
          <el-option label="已暂停" value="已暂停" />
          <el-option label="已取消" value="已取消" />
        </el-select>
        
        <el-select
          v-model="priorityFilter"
          placeholder="优先级"
          style="width: 100px"
          clearable
          @change="handleFilter"
        >
          <el-option label="高" value="high" />
          <el-option label="中" value="medium" />
          <el-option label="低" value="low" />
        </el-select>
        
        <el-button @click="resetFilters">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </div>
    </div>
    
    <!-- 项目列表 -->
    <div class="project-grid" v-loading="loading">
      <div
        class="project-card"
        v-for="project in filteredProjects"
        :key="project.id"
        @click="viewProject(project.id)"
      >
        <div class="project-header">
          <div class="project-title">
            <h3>{{ project.name }}</h3>
            <div class="project-badges">
              <el-tag
                :type="getStatusType(project.status)"
                size="small"
              >
                {{ project.status }}
              </el-tag>
              <el-tag
                :type="getPriorityType(project.priority)"
                size="small"
                effect="plain"
              >
                {{ getPriorityText(project.priority) }}
              </el-tag>
            </div>
          </div>
          <div class="project-actions">
            <el-dropdown @command="handleCommand">
              <el-button text>
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'view', id: project.id }">
                    <el-icon><View /></el-icon>
                    查看详情
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'edit', id: project.id }">
                    <el-icon><Edit /></el-icon>
                    编辑项目
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{ action: 'delete', id: project.id }"
                    divided
                  >
                    <el-icon><Delete /></el-icon>
                    删除项目
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        
        <div class="project-description">
          <p>{{ project.description || '暂无描述' }}</p>
        </div>
        
        <div class="project-progress">
          <div class="progress-info">
            <span>进度</span>
            <span>{{ project.progress }}%</span>
          </div>
          <el-progress
            :percentage="project.progress"
            :stroke-width="6"
            :show-text="false"
          />
        </div>
        
        <div class="project-meta">
          <div class="meta-item">
            <el-icon><User /></el-icon>
            <span>{{ project.manager?.username || '未分配' }}</span>
          </div>
          <div class="meta-item">
            <el-icon><Calendar /></el-icon>
            <span>{{ formatDate(project.startDate) }}</span>
          </div>
          <div class="meta-item">
            <el-icon><Clock /></el-icon>
            <span>{{ formatDate(project.endDate) }}</span>
          </div>
        </div>
        
        <div class="project-stats">
          <div class="stat-item">
            <span class="stat-number">{{ project.taskCount || 0 }}</span>
            <span class="stat-label">任务</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ project.memberCount || 0 }}</span>
            <span class="stat-label">成员</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ project.issueCount || 0 }}</span>
            <span class="stat-label">问题</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div class="empty-state" v-if="!loading && filteredProjects.length === 0">
      <el-empty description="暂无项目数据">
        <el-button type="primary" @click="createProject">
          创建第一个项目
        </el-button>
      </el-empty>
    </div>
    
    <!-- 分页 -->
    <div class="pagination" v-if="filteredProjects.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 48]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import {
  Plus,
  Search,
  Refresh,
  MoreFilled,
  View,
  Edit,
  Delete,
  User,
  Calendar,
  Clock
} from '@element-plus/icons-vue'

const router = useRouter()


const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const priorityFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 模拟项目数据
const projects = ref([
  {
    id: 1,
    name: '项目管理系统',
    description: '基于Vue 3和Spring Boot的项目管理系统',
    status: '进行中',
    priority: 'high',
    progress: 75,
    startDate: new Date('2024-01-01'),
    endDate: new Date('2024-03-31'),
    manager: { username: '张三' },
    taskCount: 25,
    memberCount: 8,
    issueCount: 3
  },
  {
    id: 2,
    name: '电商平台',
    description: '在线购物平台开发项目',
    status: '已完成',
    priority: 'medium',
    progress: 100,
    startDate: new Date('2023-10-01'),
    endDate: new Date('2023-12-31'),
    manager: { username: '李四' },
    taskCount: 45,
    memberCount: 12,
    issueCount: 0
  },
  {
    id: 3,
    name: '移动应用开发',
    description: 'React Native移动应用开发',
    status: '已暂停',
    priority: 'low',
    progress: 30,
    startDate: new Date('2024-02-01'),
    endDate: new Date('2024-06-30'),
    manager: { username: '王五' },
    taskCount: 15,
    memberCount: 5,
    issueCount: 2
  },
  {
    id: 4,
    name: '数据分析平台',
    description: '企业数据分析和可视化平台',
    status: '进行中',
    priority: 'high',
    progress: 60,
    startDate: new Date('2024-01-15'),
    endDate: new Date('2024-05-15'),
    manager: { username: '赵六' },
    taskCount: 35,
    memberCount: 10,
    issueCount: 5
  }
])

// 过滤后的项目列表
const filteredProjects = computed(() => {
  let result = projects.value
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(project => 
      project.name.toLowerCase().includes(query) ||
      (project.description && project.description.toLowerCase().includes(query))
    )
  }
  
  // 状态过滤
  if (statusFilter.value) {
    result = result.filter(project => project.status === statusFilter.value)
  }
  
  // 优先级过滤
  if (priorityFilter.value) {
    result = result.filter(project => project.priority === priorityFilter.value)
  }
  
  total.value = result.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 获取状态类型
const getStatusType = (status: string): 'success' | 'warning' | 'danger' | 'info' | 'primary' => {
  const types: Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'> = {
    '进行中': 'warning',
    '已完成': 'success',
    '已暂停': 'info',
    '已取消': 'danger'
  }
  return types[status] || 'info'
}

// 获取优先级类型
const getPriorityType = (priority: string): 'success' | 'warning' | 'danger' | 'info' | 'primary' => {
  const types: Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'> = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'success'
  }
  return types[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const texts: Record<string, string> = {
    'high': '高',
    'medium': '中',
    'low': '低'
  }
  return texts[priority] || priority
}

// 格式化日期
const formatDate = (date: Date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
}

// 重置筛选
const resetFilters = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  priorityFilter.value = ''
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 操作处理
const handleCommand = (command: { action: string; id: number }) => {
  const { action, id } = command
  
  switch (action) {
    case 'view':
      viewProject(id)
      break
    case 'edit':
      editProject(id)
      break
    case 'delete':
      deleteProject(id)
      break
  }
}

// 查看项目
const viewProject = (id: number) => {
  router.push(`/projects/${id}`)
}

// 编辑项目
const editProject = (id: number) => {
  router.push(`/projects/${id}/edit`)
}

// 删除项目
const deleteProject = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个项目吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API删除项目
    projects.value = projects.value.filter(p => p.id !== id)
    ElMessage.success('项目删除成功')
  } catch {
    // 用户取消删除
  }
}

// 创建项目
const createProject = () => {
  router.push('/projects/create')
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 这里应该调用API加载项目数据
    // await projectStore.fetchProjects()
    await new Promise(resolve => setTimeout(resolve, 500))
  } catch (error) {
    console.error('加载项目数据失败:', error)
    ElMessage.error('加载项目数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.project-list {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-right {
  display: flex;
  gap: 12px;
}

.project-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.project-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  cursor: pointer;
  border: 1px solid transparent;
}

.project-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  border-color: #409eff;
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.project-title h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.project-badges {
  display: flex;
  gap: 8px;
}

.project-actions {
  flex-shrink: 0;
}

.project-description {
  margin-bottom: 16px;
}

.project-description p {
  margin: 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.project-progress {
  margin-bottom: 16px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.progress-info span:first-child {
  color: #666;
}

.progress-info span:last-child {
  color: #333;
  font-weight: 600;
}

.project-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #666;
}

.meta-item .el-icon {
  font-size: 14px;
}

.project-stats {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-section {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-right {
    justify-content: center;
  }
  
  .project-grid {
    grid-template-columns: 1fr;
  }
  
  .project-meta {
    flex-direction: column;
  }
}
</style>